import time
import threading
import subprocess, shlex
from bottle import route, view

_DVDSERVER = dict()
_CONNECTION_ALIVE = dict()

@route("/dvd/<lang>/<title:int>")
@view("dvdplayer")
def stream_dvd(lang, title):
	id = len(_DVDSERVER)
	url = "localhost:8082/{id}.mpeg".format(id=id)
	cmd = "cvlc -Ihttp -vvv dvdsimple:///dev/dvd#{title} –audio-language={lang} --sout '#standard{{access=http,mux=mpeg,dst={url}}}'".format(lang=lang, url=url, title=title)
	cmd = shlex.split(cmd)
	_DVDSERVER[id] = subprocess.Popen(cmd)
	_CONNECTION_ALIVE[id] = time.time()
	def check_alive():
		while time.time() - _CONNECTION_ALIVE[id] < 2:
			print(time.time() - _CONNECTION_ALIVE[id])
			time.sleep(1)
		_DVDSERVER[id].kill()
		del _DVDSERVER[id]
		del _CONNECTION_ALIVE[id]
	threading.Thread(target=check_alive).start()
	return dict(id=id, src="http://" + url)
	
@route("/dvdalive/<id:int>")
def alive(id):
	_CONNECTION_ALIVE[id] = time.time()
